import _ from 'lodash';
import { message, Modal } from 'antd';
import { WeaLocaleProvider } from "ecCom";
import EE from './event';
import { eventTypes } from '../../../../../constants/events';

const { DOMLOAD, ONSUBMIT, ONBEFORESUBMIT } = eventTypes;
const { confirm } = Modal;
const getLabel = WeaLocaleProvider.getLabel;

// 解决 Modal.confirm 关闭后未自动清除 body上样式的问题
const setBodyOverflow = () => { document.body.style.overflow = 'auto';};
const formatSelectVal = (com, value) => {
  const { options } = com.config;
  const vals = [];

  options.forEach(({ showname, key }, i) => {

    if (value && value.length > 0 && value.indexOf(showname) > -1) {
      vals.push({
        key: key,
        value: showname
      })
    }
  })
  
  return vals;
}

export default class EdcForm {
  constructor(store) {
    
   this.store = store;
  }
  
  bindEvent(evtName, fieldids, handler) {
    const events = [DOMLOAD, ONSUBMIT, ONBEFORESUBMIT];
    const result = events.indexOf(evtName);

    if (result > -1) {
      handler = fieldids;
      EE.on(evtName, handler);
      return;
    }

    const fieldidsArr = fieldids.split(",");

    fieldidsArr.forEach(id => {
      const finalEvtName = evtName + '_' + id;
      const components = this.store.components;
      const com = components.find(c => c.uuid === id);

      if (evtName === 'fieldValueChange' && com.type === 'ADDRESS') {
        const childrenComs = components.filter(c => c.pid === com.uuid);

        childrenComs.forEach(cc => {
          const finalEvtName = evtName + '_' + cc.uuid;

          EE.on(finalEvtName, handler);
        })
        return;
      }

      EE.on(finalEvtName, handler);
    });
  }

  setFieldValue(fieldidOrIndex, value) {
    const components = this.store.components;
    const fieldArr = fieldidOrIndex.split(",");
    const valueArr = Array.isArray(value) ? value : value.split(",");
    const len = fieldArr.length;

    if(len === 0) return;

    fieldArr.forEach((id, index) => {
      const com = components.find(c => c.uuid === id);

      if (com.type === 'SELECT' || com.type === 'COMBOBOX') {
        com.value = formatSelectVal(com, valueArr);
        return;
      }

      if(com.type === 'ADDRESS') {
        const { province: p, city: ci, district: dis, detail: det } = com.config;
        const province = components.find(c => c.uuid === p.uuid);
        const city = components.find(c => c.uuid === ci.uuid);
        const district = components.find(c => c.uuid === dis.uuid);
        const detail = components.find(c => c.uuid === det.uuid);

        p.value = province.value = valueArr[0];
        ci.value = city.value = valueArr[1];
        dis.value = district.value = valueArr[2];
        det.value = detail.value = valueArr[3];
        return;
      }

      if (com.type === 'DATATABLE') {
        const { coms } = com.config;
      
        coms && coms.forEach((com, colIndex) => {
          valueArr.forEach((rowVals, rowIndex) => {
            if (com.type === 'SELECT' || com.type === 'COMBOBOX') {
              valueArr[rowIndex][colIndex] = formatSelectVal(com, valueArr[rowIndex][colIndex]);
            } else {
              valueArr[rowIndex][colIndex] = valueArr[rowIndex][colIndex] || '';
            }
          });
        });

        com.value = valueArr;
        return;
      }
      
      if (valueArr[index]) {
        com.value = valueArr[index];
      }
    });

    setTimeout(() => {
      this.store.setComponents(components);
    }, 200)
  }

  getFieldValue(fieldidOrIndex) {
    const components = this.store.components;
    const fieldArr = fieldidOrIndex.split(",");
    const len = fieldArr.length;

    if(len === 0) return "";

    if(len === 1) {
      const com = components.find(c => c.uuid === fieldidOrIndex);

      if(com.type === 'ADDRESS') {
       
        const { province: p, city: ci, district: dis, detail: det } = com.config;

        const province = components.find(c => c.uuid === p.uuid);
        const city = components.find(c => c.uuid === ci.uuid);
        const district = components.find(c => c.uuid === dis.uuid);
        const detail = components.find(c => c.uuid === det.uuid);

        return `${province.value}${city.value}${district.value}${detail.value}`;
      }

      return com.value;
    }

    if(len > 1) {
      let values = [];

      fieldArr.forEach(id => {
        const com = componets.find(c => c.uuid === id);

        if(com){
          values.push(com.value);
        }
      });
      return values;
    }
  }

  getUrlParamValue(key) {
    if (!key) return '';

    const href = window.location.href;
    const [,paramUrl] = href.split("?");
    const params = {};

    if (!paramUrl) return ''; 

    paramUrl.split('&').map( param => {
      const [key, value] = param.split('=');

      params[key] = value;
    });

    const paramValue = params[key] || '';
    
    return paramValue;
  }

  ajax(url, options) {
    let settings = options;
    settings.url = url;

    return jQuery.ajax(settings);
  }
  
  message(msgType, msgStr) {
    const types = ["info", "success", "error", "warning"];
    const result = types.indexOf(msgType);

    if (result > -1) {
      message[msgType](msgStr);
    }
  }

  alert(msgStr) {
    Modal.warning({
      title: getLabel('558', '提示'),
      okText: getLabel('826', '确定'),
      content: msgStr,
      onCancel: setBodyOverflow,
      onOk: setBodyOverflow,
    });
  }

  confirm(msg, okFunc=()=>{}, cancelFunc=()=>{}) {
    let opts = {
      title: '确认框',
      okText: '确定',
      cancelText: '取消',
    }

    if (_.isString(msg)) {
      let onOk = () => {
        okFunc();
        setBodyOverflow();
      }
  
      let onCancel = () => {
        cancelFunc();
        setBodyOverflow();
      }
      
      opts = {
        ...opts,
        onOk,
        onCancel,
        content: msg
      }
    }

    if (_.isObject(msg)) {
      opts = {
        content: msg.content, 
        okText: msg.okText, 
        cancelText: msg.cancelText, 
        onOk: () => { msg.onOk(); setBodyOverflow(); },
        onCancel: () => { msg.onCancel(); setBodyOverflow(); },  
      }
    }

    confirm(opts);
  }
}
